var pathRequestUrl;
var START_INDEX = 3;
var date_format_string = 'm/Y';
var date_sql_format_string = 'Y-m-d';

Ext.onReady(function(){
    Ext.QuickTips.init();
    pathRequestUrl = 'ReportYieldRevenueInformation_Data.php';
    
    var partnerRecord = [{
        name: 'partner_id',
        type: 'string'
    }, {
        name: 'partner_number',
        type: 'string'
    }, {
        name: 'partner_name',
        type: 'string'
    }];
    
    var partnerObj = Ext.data.Record.create(partnerRecord);
    
    var storePartner = new Ext.data.Store({
        reader: new Ext.data.JsonReader({
            root: 'data',
            totalProperty: 'count',
            id: 'partner_id'
        }, partnerObj),
        proxy: new Ext.data.HttpProxy({
            url: pathRequestUrl
        }),
        autoLoad: true
    });
    
    storePartner.on('beforeload', function(){
        storePartner.baseParams.action = 'getPartner';
    });
    
    var partnerPriceRecord = [{
        name: 'id',
        type: 'string'
    }, {
        name: 'price',
        type: 'string'
    }];
    
    var partnerPriceObj = Ext.data.Record.create(partnerPriceRecord);
    
    var storePartnerPrices = new Ext.data.Store({
        reader: new Ext.data.JsonReader({
            root: 'data',
            id: 'id'
        }, partnerPriceObj),
        proxy: new Ext.data.HttpProxy({
            url: pathRequestUrl
        }),
        autoLoad: false
    });
    
    storePartnerPrices.on('beforeload', function(){
        storePartnerPrices.baseParams.action = 'getPartnerPrices';
    });
    
    var storeObject = new Ext.data.Store({
        reader: new Ext.data.JsonReader({
            root: 'data',
            totalProperty: 'count',
            id: 'object_id',
            fields: ['object_id', 'object_number', 'object_name']
        }),
        proxy: new Ext.data.HttpProxy({
            url: pathRequestUrl
        }),
        autoLoad: true
    });
    
    storeObject.on('beforeload', function(){
        storeObject.baseParams.start = 0;
        storeObject.baseParams.limit = 100;
        storeObject.baseParams.action = 'getObject';
    });
    
    var resultTplObject = new Ext.XTemplate('<tpl for="."><div class="search-item">', '<span>{object_number} | {object_name}</span><br />', '</div></tpl>');
    
    var cbObject = new Ext.form.ComboBox({
        id: 'cbObject',
        store: storeObject,
        fieldLabel: 'Tên',
        forceSelection: true,
        displayField: 'object_name',
        valueField: 'object_id',
        typeAhead: false,
        triggerAction: 'all',
        emptyText: 'Chọn tên',
        allowBlank: false,
        tpl: resultTplObject,
        selectOnFocus: true,
        editable: true,
        width: 300,
        pageSize: 100,
        lazyRender: true,
        listWidth: 400,
        itemSelector: 'div.search-item',
        minChars: 1
    });
    
    var cbSubjectName = new Ext.form.ComboBox({
        id: 'cbSubjectName',
        name: 'cbSubjectName',
        store: storePartner,
        fieldLabel: 'Đối tác',
        forceSelection: true,
        displayField: 'partner_name',
        valueField: 'partner_id',
        allowBlank: false,
        typeAhead: true,
        mode: 'local',
        triggerAction: 'all',
        emptyText: 'Chọn đối tác',
        selectOnFocus: true,
        editable: false,
        width: 300,
        minListWidth: 300,
        lazyRender: true,
        listeners: {
            select: function(combo, record, index){
		Ext.getCmp('cbPartnerPrices').setValue('');
		storePartnerPrices.load({
		    params: {partner_id: record.data.partner_id}
		})
            },
            change: function(e){
            }
        }
    });
    
    var cbPartnerPrices = new Ext.form.ComboBox({
        id: 'cbPartnerPrices',
        name: 'cbPartnerPrices',
        store: storePartnerPrices,
        fieldLabel: 'Giá',
        forceSelection: true,
        displayField: 'price',
        valueField: 'id',
        allowBlank: true,
        typeAhead: true,
        mode: 'local',
        triggerAction: 'all',
        emptyText: 'Chọn giá',
        selectOnFocus: true,
        editable: true,
        width: 80,
        minListWidth: 300,
        lazyRender: true,
        listeners: {
            select: function(combo, record, index){            
            },
            change: function(e){
            }
        }
    });
    
    var storeRelease = new Ext.data.ArrayStore({
        fields: [{
            name: 'release'
        }, {
            name: 'name'
        }, ],
        data: [[0, 'Không độc quyền'], [1, 'Độc quyền']]
    });
    
    var cboRelease = new Ext.form.ComboBox({
        id: 'cboRelease',
        store: storeRelease,
        forceSelection: true,
        displayField: 'name',
        valueField: 'release',
        fieldLabel: 'Độc quyền',
        typeAhead: false,
        triggerAction: 'all',
        mode: 'local',
        forceSelection: true,
        emptyText: 'Chọn độc quyền',
        triggerAction: 'all',
        allowBlank: true,
        editable: true,
        width: 130,
        minListWidth: 100,
        lazyRender: true,
        selectOnFocus: true
    });
    
    var generalTab = new Ext.Panel({
        frame: true,
        title: '',
        //height: 260,
        id: 'generalTab',
        items: [{
            layout: 'column',
            items: [{
                columnWidth: .3,
                layout: 'form',
                labelWidth: 70,
                items: [{
                    xtype: 'hidden',
                    id: 'selectedTimeValue',
                    value: '1'
                }, new Ext.form.RadioGroup({
                    fieldLabel: 'Thời gian',
                    columns: 1,
                    id: "timename",
                    items: [{
                        boxLabel: 'Tháng',
                        name: 'timename',
                        inputValue: 'month',
                        checked: true
                    }, {
                        boxLabel: 'Quý',
                        name: 'timename',
                        inputValue: 'quarter'
                    }, {
                        boxLabel: 'Từ tháng',
                        name: 'timename',
                        inputValue: 'frommonth'
                    }]
                })]
            }, {
                columnWidth: .7,
                layout: 'form',
                labelWidth: 5,
                id: 'col1',
                items: [{
                    layout: 'column',
                    items: [{
                        columnWidth: .25,
                        layout: 'form',
                        labelWidth: 5,
                        items: [{
                            xtype: 'spinnerfield',
                            name: 'month2',
                            id: 'month2',
                            width: 70,
                            length: 4,
                            minValue: 1,
                            maxValue: 12,
                            allowDecimals: false,
                            incrementValue: 1,
                            accelerate: true,
                            value: (new Date()).format('m')
                        }]
                    }, {
                        columnWidth: .7,
                        layout: 'form',
                        labelWidth: 30,
                        items: [{
                            xtype: 'spinnerfield',
                            name: 'year2',
                            id: 'year2',
                            width: 70,
                            length: 4,
                            minValue: 2010,
                            maxValue: 2020,
                            allowDecimals: false,
                            incrementValue: 1,
                            accelerate: true,
                            fieldLabel: 'Năm',
                            value: (new Date()).format('Y')
                        }]
                    }]
                }, {
                    layout: 'column',
                    items: [{
                        columnWidth: .25,
                        layout: 'form',
                        labelWidth: 5,
                        items: [{
                            xtype: 'spinnerfield',
                            name: 'quarter3',
                            id: 'quarter3',
                            width: 70,
                            length: 4,
                            minValue: 1,
                            maxValue: 4,
                            allowDecimals: false,
                            incrementValue: 1,
                            accelerate: true,
                            value: 1
                        }]
                    }, {
                        columnWidth: .7,
                        layout: 'form',
                        labelWidth: 30,
                        items: [{
                            xtype: 'spinnerfield',
                            name: 'year3',
                            id: 'year3',
                            width: 70,
                            length: 4,
                            minValue: 2010,
                            maxValue: 2020,
                            allowDecimals: false,
                            incrementValue: 1,
                            accelerate: true,
                            fieldLabel: 'Năm',
                            value: (new Date()).format('Y')
                        }]
                    }]
                }, {
                    layout: 'column',
                    items: [{
                        columnWidth: .22,
                        layout: 'form',
                        labelWidth: 5,
                        items: [{
                            xtype: 'spinnerfield',
                            name: 'frommonth7',
                            id: 'frommonth7',
                            width: 70,
                            length: 4,
                            minValue: 1,
                            maxValue: 12,
                            allowDecimals: false,
                            incrementValue: 1,
                            accelerate: true,
                            value: (new Date()).format('m')
                        }]
                    }, {
                        columnWidth: .25,
                        layout: 'form',
                        labelWidth: 5,
                        items: [{
                            xtype: 'spinnerfield',
                            name: 'fromyear7',
                            id: 'fromyear7',
                            width: 70,
                            length: 4,
                            minValue: 2010,
                            maxValue: 2020,
                            allowDecimals: false,
                            incrementValue: 1,
                            accelerate: true,
                            value: (new Date()).format('Y')
                        }]
                    }, {
                        columnWidth: .27,
                        layout: 'form',
                        labelWidth: 20,
                        items: [{
                            xtype: 'spinnerfield',
                            name: 'tomonth7',
                            id: 'tomonth7',
                            width: 70,
                            length: 4,
                            minValue: 1,
                            maxValue: 12,
                            labelSeparator: '',
                            fieldLabel: 'Đến',
                            allowDecimals: false,
                            incrementValue: 1,
                            accelerate: true,
                            value: (new Date()).format('m')
                        }]
                    }, {
                        columnWidth: .25,
                        layout: 'form',
                        labelWidth: 5,
                        items: [{
                            xtype: 'spinnerfield',
                            name: 'toyear7',
                            id: 'toyear7',
                            width: 70,
                            length: 4,
                            minValue: 2010,
                            maxValue: 2020,
                            allowDecimals: false,
                            incrementValue: 1,
                            accelerate: true,
                            value: (new Date()).format('Y')
                        }]
                    }]
                }]
            }]
        }, {
            layout: 'form',
            labelWidth: 100,
            items: [{
                xtype: 'fieldset',
                title: 'Đối tác',
                autoHeight: true,
                items: [cbSubjectName]
            }, {
                xtype: 'fieldset',
                title: 'Giá Đối tác',
                autoHeight: true,
                items: [cbPartnerPrices]
            }]
        }, {
            layout: 'form',
            labelWidth: 100,
            items: [{
                xtype: 'fieldset',
                title: 'Ca sĩ/Nhạc sĩ',
                autoHeight: true,
                items: [cbObject, {
					xtype: 'radiogroup',
					id: 'object_type',
					fieldLabel: 'Loại',
					value: 1,
					items: [{
						boxLabel: 'Ca sĩ',
						name: 'rb-type',
						inputValue: 1
					}, {
						boxLabel: 'Nhạc sĩ',
						name: 'rb-type',
						inputValue: 2
					}]
				}, cboRelease]
            }]
        }]
    });
    
    var dataSinger = new Ext.FormPanel({
        frame: true,
        title: 'Biên bản đối soát theo tháng, quý',
        width: 550,
        renderTo: 'ReportYieldRevenueTables',
        iconCls: 'form-icon',
        url: pathRequestUrl,
        fileUpload: true,
        items: [generalTab],
        buttons: [{
            text: 'In báo cáo',
            handler: function(){
                if (dataSinger.getForm().isValid()) {
                    var fd = baseGetFromDateRank();
                    var td = baseGetToDateRank();
                    var release = isEmpty(Ext.getCmp('cboRelease').getValue()) ? -1 : Ext.getCmp('cboRelease').getValue();
                    
                    window.open(pathRequestUrl + '?action=export' +
                                '&partnerId=' + Ext.getCmp('cbSubjectName').getValue() +
                                '&partnerPrice=' + Ext.getCmp('cbPartnerPrices').getRawValue() +
                                '&partnerPriceId=' + Ext.getCmp('cbPartnerPrices').getValue() + 
                    		'&object=' + Ext.getCmp('cbObject').getValue() + 
                    		'&type=' + Ext.getCmp('object_type').getValue().inputValue + 
                    		'&release=' + release + 
                    		'&fdate=' + fd + '&tdate=' + td, null, 
                    		"height=200,width=400,status=yes,toolbar=no,menubar=no,location=no");
                }
            }
        }, {
            text: 'Thoát'
        }]
    });
    
    var baseGetFromDateRank = function(){
        var type = Ext.getCmp('timename').getValue().inputValue;
        switch (type) {
            case 'month':
                var m = Ext.getCmp('month2').getValue().toString();
                if (m.length < 2) {
                    m = '0' + m;
                }
                var d = Ext.getCmp('year2').getValue() + '/' + m + '/02';
                return (new Date(d)).getFirstDateOfMonth().dateFormat(date_sql_format_string);
                break;
            case 'quarter': // quy
                var q = Ext.getCmp('quarter3').getValue();
                var y = Ext.getCmp('year3').getValue();
                var d = '';
                if (q == 1) {
                    d = y + '/01/02';
                }
                else 
                    if (q == 2) {
                        d = y + '/04/02';
                    }
                    else 
                        if (q == 3) {
                            d = y + '/07/02';
                        }
                        else 
                            if (q == 4) {
                                d = y + '/10/02';
                            }
                return (new Date(d)).getFirstDateOfMonth().dateFormat(date_sql_format_string);
                break;
            case 'frommonth': // tu thang
                var fm = Ext.getCmp('frommonth7').getValue().toString();
                if (fm.length < 2) {
                    fm = '0' + fm;
                }
                var fy = Ext.getCmp('fromyear7').getValue();
                var d = fy + '/' + fm + '/02';
                return (new Date(d)).getFirstDateOfMonth().dateFormat(date_sql_format_string);
                break;
            default:
                console.debug('fail');
        }
    };
    
    var baseGetToDateRank = function(){
        var type = Ext.getCmp('timename').getValue().inputValue;
        switch (type) {
            case 'month':
                var m = Ext.getCmp('month2').getValue().toString();
                if (m.length < 2) {
                    m = '0' + m;
                }
                var d = Ext.getCmp('year2').getValue() + '/' + m + '/02';
                return (new Date(d)).getLastDateOfMonth().dateFormat(date_sql_format_string);
                break;
            case 'quarter': // quy
                var q = Ext.getCmp('quarter3').getValue();
                var y = Ext.getCmp('year3').getValue();
                var d = '';
                if (q == 1) {
                    d = y + '/03/02';
                }
                else 
                    if (q == 2) {
                        d = y + '/06/02';
                    }
                    else 
                        if (q == 3) {
                            d = y + '/09/02';
                        }
                        else 
                            if (q == 4) {
                                d = y + '/12/02';
                            }
                return (new Date(d)).getLastDateOfMonth().dateFormat(date_sql_format_string);
                break;
            case 'frommonth':
                var tm = Ext.getCmp('tomonth7').getValue().toString();
                if (tm.length < 2) {
                    tm = '0' + tm;
                }
                var ty = Ext.getCmp('toyear7').getValue();
                var d = ty + '/' + tm + '/02';
                return (new Date(d)).getLastDateOfMonth().dateFormat(date_sql_format_string);
                break;
            default:
                console.debug('fail');
        }
    };
});
